package com.cmsz.shuang.booter.web;


import org.hibernate.validator.internal.constraintvalidators.bv.NullValidator;
import org.springframework.beans.factory.annotation.Autowired;

import com.cmsz.shuang.booter.dao.AccessMapper;
import com.cmsz.shuang.booter.model.UserPo;
import com.vaadin.annotations.Theme;
import com.vaadin.data.Validator;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Page;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinSession;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Notification.Type;
import com.vaadin.ui.Panel;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;

@SpringUI(path="/login")
@Theme("valo")
public class LoginUI extends UI {
	
	@Autowired
	private AccessMapper accessmapper;
	
	@Override
	protected void init(VaadinRequest request) {
		
		Page.getCurrent().setTitle("Login Page");
		
		Panel p1= new Panel();
		p1.setCaption("Login");
		
		FormLayout form = new FormLayout();
		TextField tf1 = new TextField("Name");
		tf1.setIcon(FontAwesome.USER);
		tf1.setRequired(true);
		tf1.addValidator((Validator) new com.vaadin.data.validator.NullValidator("Must be given ", false));
		form.addComponent(tf1);
		
		PasswordField tf2 = new PasswordField("Password");
		tf2.setIcon(FontAwesome.HEART);
		tf2.setRequired(true);
		tf2.addValidator((Validator) new com.vaadin.data.validator.NullValidator("Must be given ", false));
		form.addComponent(tf2);
		
		Button btn1 = new Button("Login");
		btn1.addClickListener(new Button.ClickListener(){

			@Override
			public void buttonClick(ClickEvent event) {
				
				String name= tf1.getValue();
				String pwd = tf2.getValue();
				if(name == null || name.length()< 1 || pwd == null || pwd.length() <1 )
				{
					Notification.show("input error, name = "+ name +" pwd=" + pwd);
					return ;
				}
				
				UserPo userpo = accessmapper.getUserPoByName(name);
				if(userpo !=null )
				{
					if(pwd.equals(userpo.getPassword()) ){
						Notification.show("Login success, name = "+ name +" pwd=" + pwd);
						VaadinSession.getCurrent().setAttribute("UserPO", userpo);
						
						Page.getCurrent().setLocation("/main");
						
					}else
					{
						Notification.show("password error, name = "+ name +" pwd=" + pwd,Notification.Type.ERROR_MESSAGE);
					}
					
				}else
				{
					Notification.show("name is not exist, name = "+ name +" pwd=" + pwd, Notification.Type.WARNING_MESSAGE);
				}
			}
		});
		
		form.addComponent(btn1);
		p1.setContent(form);
		setContent(p1);
		
		
	}

}
